import { login, smsCodeLogin ,logout} from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {encrypt} from '@/utils/index'
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles:null,
    mobile:'',
    sellerId:'',
    userId:'',
    isMange:'',
    position:'',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLE: (state, roles) => {
      state.roles = roles;
    },
    SET_SELLERID: (state, id) => {
      state.sellerId = id;
    },
    SET_MOBILE:(state, mobile) =>{
      state.mobile = mobile
    },
    SET_USERID: (state, id) => {
      state.userId = id;
    },
    SET_isMange: (state, isMange) => {
      state.isMange = isMange;
    },
    SET_roleName: (state, roleName) => {
      state.roleName = roleName;
    },
  },

  actions: {
    // 登录
    Login({ commit }, param) {
      return new Promise((resolve, reject) => {
        let password = encrypt(param.data.password)
        login(param.data.mobile, password).then(response => {
          const data = response;
          const userInfo = {};
          userInfo.permissions = response.permissions;
          userInfo.subscriberInfo = response.subscriberInfo;
          userInfo.newMenu = response.newMenu;
          localStorage.setExpire('userInfo', userInfo, 3600 * 1000 * 24);
          const tokenStr = data.token;
          setToken(tokenStr);
          commit('SET_TOKEN', tokenStr);
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        const data = localStorage.getExpire('userInfo');
        if (data) { // 验证返回用户信息是否有值
          commit('SET_USERID', data.subscriberInfo.userId);
          commit('SET_ROLE', data.permissions);
          commit('SET_NAME', data.subscriberInfo.realName);
          commit('SET_AVATAR', '');
          commit('SET_MOBILE',data.subscriberInfo.mobile);
          commit('SET_isMange',data.subscriberInfo.isMange);
          commit("SET_roleName",data.subscriberInfo.roleName)
          resolve(data)
        } else {
          console.log("错误")
          reject('getInfo: roles must be a non-null array !')
        }
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(()=>{
          commit('SET_TOKEN', '')
          commit('SET_ROLES', '')
          localStorage.clear();
          removeToken()
          resolve()
        })

      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        localStorage.clear();
        removeToken();
        resolve()
      })
    }
  }
}

export default user
